import Vue from 'vue'
import Vuex from 'vuex'
import { setItem, getItem, removeItem } from '@/utils/storage.js'
import { reqGetChannels, reqGetAllChannels } from '@/api/channels.js'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    tokenInfo: getItem('token') || {},
    channels: [],
    allchannels: []
  },
  mutations: {
    setTokenInfo (state, tokenObj) {
      state.tokenInfo = tokenObj || {}
      // localStorage.setItem('token', JSON.stringify(tokenObj))
      setItem('token', tokenObj)
    },
    setUserInfo (state, info) {
      setItem('userInfo', info)
    },
    getUserInfo (state) {
      return getItem('userInfo')
    },

    removeToken (state) {
      state.tokenInfo = {}
      removeItem('token')
      setItem('userInfo', null)
    },
    setChannels (state, channels) {
      state.channels = channels
    },
    setAllChannels (state, allchannels) {
      state.allchannels = allchannels
    },
    addChannels (state, channel) {
      state.channels.push(channel)
    },
    delChannels (state, channel) {
      state.channels = state.channels.filter(item => item.id !== channel.id)
    }
  },
  actions: {
    async getChannelAsync (context) {
      // const res = await reqGetChannels()
      // console.log(res.data.data.channels)
      context.commit('setChannels', '/question')
    },
    async getAllChannelAsync (context) {
      // const res = await reqGetAllChannels()
      // context.commit('setAllChannels', res.data.data.channels)
    }
  },
  getters: {
    optionalChannels: (state) => {
      const result = state.allchannels.filter(channel => {
        const index = state.channels.findIndex(item => item.id === channel.id)
        return index === -1
      })
      return result
    },
    getUserInfo: (state) => {
      return getItem('userInfo')
    }

  },
  modules: {
  }
})
